package com.bootdo.jiashan.service.impl;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.MoneyConvert;
import com.bootdo.common.utils.RejectUtil;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.jiashan.dao.SaleOrderInfoDao;
import com.bootdo.jiashan.dao.SupplyProductDao;
import com.bootdo.jiashan.domain.SaleOrderInfoDO;
import com.bootdo.jiashan.model.SupplyProductModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.bootdo.jiashan.dao.SaleOrderDao;
import com.bootdo.jiashan.domain.SaleOrderDO;
import com.bootdo.jiashan.service.SaleOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;


@Service
@Slf4j
public class SaleOrderServiceImpl implements SaleOrderService {
	@Autowired
	private SaleOrderDao saleOrderDao;

	@Autowired
	private SaleOrderInfoDao saleOrderInfoDao;

	@Autowired
	private SupplyProductDao supplyProductDao;
	
	@Override
	public SaleOrderDO get(Integer id){
		SaleOrderDO saleOrderDO =  saleOrderDao.get(id);
		Map<String, Object> map = new HashMap<>();
		map.put("saleOrderId",saleOrderDO.getId());
		List<SaleOrderInfoDO> infoDOList = saleOrderInfoDao.list(map);
		saleOrderDO.setSaleOrderInfoDOS(infoDOList);
		return saleOrderDO;
	}
	
	@Override
	public List<SaleOrderDO> list(Map<String, Object> map){
		return saleOrderDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return saleOrderDao.count(map);
	}
	
	@Override
	public int save(SaleOrderDO saleOrder) throws IllegalAccessException {
		RejectUtil.nullToEmptyStrOr0(saleOrder);
		saleOrder.setCtime(new Date());
		saleOrder.setId(null);
		saleOrder.setPrice(BigDecimal.ZERO);
		List<SaleOrderInfoDO> saleOrderInfoDOS = saleOrder.getSaleOrderInfoDOS();
		Integer count = 0;
		if(CollectionUtils.isNotEmpty(saleOrderInfoDOS)){
			for (SaleOrderInfoDO saleOrderInfoDO : saleOrderInfoDOS) {
				Integer infoCount = saleOrderInfoDO.getCount() == null ? 0: saleOrderInfoDO.getCount();
				count += infoCount;
			}
		}
		saleOrder.setCount(count);
		saleOrder.setCtime(new Date());
		saleOrder.setUtime(new Date());
		saleOrderDao.save(saleOrder);

		if(CollectionUtils.isNotEmpty(saleOrderInfoDOS)){
			for (SaleOrderInfoDO saleOrderInfoDO : saleOrderInfoDOS) {
				saleOrderInfoDO.setSaleOrderId(saleOrder.getId());
				RejectUtil.nullToEmptyStrOr0(saleOrderInfoDO);
				saleOrderInfoDO.setId(null);
				saleOrderInfoDO.setCtime(new Date());
				saleOrderInfoDO.setUtime(new Date());
				saleOrderInfoDao.save(saleOrderInfoDO);
			}
		}
		return 1;
	}
	
	@Override
	@Transactional
	public int update(SaleOrderDO saleOrder,String removeIds) throws IllegalAccessException {
		// 删除
		if(StringUtils.isNotBlank(removeIds)){
			String[] array = removeIds.split(",");
			for (String id : array) {
				saleOrderInfoDao.remove(Integer.parseInt(id));
			}
		}

		// 保存和修改货品信息
		Date updateDate = new Date();
		List<SaleOrderInfoDO> infoDOS = saleOrder.getSaleOrderInfoDOS();
		if(CollectionUtils.isNotEmpty(infoDOS)){
			for (SaleOrderInfoDO infoDO : infoDOS) {
				infoDO.setUtime(updateDate);
				if(infoDO.getId() == null || infoDO.getId() == 0){
					if(StringUtils.isBlank(infoDO.getProductName())
						&& StringUtils.isBlank(infoDO.getProductNorm())
						&& infoDO.getCount() == null){
						continue;
					}
					RejectUtil.nullToEmptyStrOr0(infoDO);
					infoDO.setId(null);
					infoDO.setSaleOrderId(saleOrder.getId());
					infoDO.setCtime(new Date());
					infoDO.setUtime(new Date());
					saleOrderInfoDao.save(infoDO);
				}else{
					saleOrderInfoDao.update(infoDO);
				}
			}
		}

		// 修改销售单
		Integer count = 0;
		if(CollectionUtils.isNotEmpty(infoDOS)){
			for (SaleOrderInfoDO saleOrderInfoDO : infoDOS) {
				Integer infoCount = saleOrderInfoDO.getCount() == null ? 0: saleOrderInfoDO.getCount();
				count += infoCount;
			}
		}
		saleOrder.setCount(count);
		saleOrder.setUtime(updateDate);
		return saleOrderDao.update(saleOrder);
	}
	
	@Override
	public int remove(Integer id){
		return saleOrderDao.remove(id);
	}
	
	@Override
	public int batchRemove(Integer[] ids){
		return saleOrderDao.batchRemove(ids);
	}

	@Override
	public XSSFWorkbook exportExcel(Integer saleOrderId, HttpServletResponse response) {
		SaleOrderDO saleOrderDO = saleOrderDao.get(saleOrderId);

		response.setHeader("Content-Disposition", "attachment;filename=" + saleOrderDO.getTitle() +".xlsx");
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);


		Map<String, Object> map = new HashMap<>();
		map.put("saleOrderId",saleOrderDO.getId());
		List<SaleOrderInfoDO> infoDOList = saleOrderInfoDao.list(map);

		Map<String,List<String>> queryMap = new HashMap<>();
		Map<String,List<SupplyProductModel>> supplyProductMap = new HashMap<>();

		for (SaleOrderInfoDO saleOrderInfoDO : infoDOList) {
			List<String> normList = queryMap.get(saleOrderInfoDO.getProductName());
			if(CollectionUtils.isNotEmpty(normList)){
				normList.add(saleOrderInfoDO.getProductNorm());
			}else{
				normList = new ArrayList<>();
				normList.add(saleOrderInfoDO.getProductNorm());
				queryMap.put(saleOrderInfoDO.getProductName(),normList);
			}

			Map productMap = new HashMap();
			productMap.put("name",saleOrderInfoDO.getProductName());
			productMap.put("norm",saleOrderInfoDO.getProductNorm());
			List<SupplyProductModel> supplyProductModelList = supplyProductDao.list(productMap);
			String key = saleOrderInfoDO.getProductName()+"_"+saleOrderInfoDO.getProductNorm();
			supplyProductMap.put(key,supplyProductModelList);
		}


		XSSFWorkbook xwk = new XSSFWorkbook();
		XSSFSheet xssfSheet = xwk.createSheet(saleOrderDO.getTitle());
		Row firstNameRow = xssfSheet.createRow(0);
		Row secondNormRow = xssfSheet.createRow(1);

		CellStyle cellStyle = xwk.createCellStyle();
		cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

		int nameIndex = 0;
		int normIndex = 0;
		for (Map.Entry<String, List<String>> queryMapEntry : queryMap.entrySet()) {
			String productName = queryMapEntry.getKey();
			List<String> productNorms = queryMapEntry.getValue();
			xssfSheet.addMergedRegion(new CellRangeAddress(0,0,nameIndex,nameIndex + productNorms.size()*3 - 1));
			Cell nameCell = firstNameRow.createCell(nameIndex);
			nameCell.setCellValue(productName);
			nameCell.setCellStyle(cellStyle);
			nameIndex += productNorms.size()*3;

			for (String productNorm : productNorms) {
				xssfSheet.addMergedRegion(new CellRangeAddress(1,1,normIndex,normIndex+3-1));
				Cell normCell = secondNormRow.createCell(normIndex);
				normCell.setCellValue(productNorm);
				normCell.setCellStyle(cellStyle);
//				String contentKey = productName+"_"+productNorm;
//				List<SupplyProductModel> supplyProductModelList = supplyProductMap.get(contentKey);

				Map productMap = new HashMap();
				productMap.put("name",productName);
				productMap.put("norm",productNorm);
				List<SupplyProductModel> supplyProductModelList = supplyProductDao.list(productMap);

				if(CollectionUtils.isNotEmpty(supplyProductModelList)){
					log.info("productNorm:{},normIndex:{},supplyProductModelList:{} ",productNorm,normIndex, JSON.toJSONString(supplyProductModelList));
					Integer contentRowIndex = 2;
					for (SupplyProductModel supplyProductModel : supplyProductModelList) {
						Row row = xssfSheet.getRow(contentRowIndex);
						if(row == null){
							row = xssfSheet.createRow(contentRowIndex);
						}
						row.createCell(normIndex).setCellValue(MoneyConvert.centToDollarForString(supplyProductModel.getUnitPrice()));
						row.createCell(normIndex+1).setCellValue(supplyProductModel.getSupplyName());
						String phone = StringUtils.isNotBlank(supplyProductModel.getPhone())?supplyProductModel.getPhone():"";
						row.createCell(normIndex+2).setCellValue(phone+"/"+supplyProductModel.getContactMobile());
						contentRowIndex++;
					}
				}
				normIndex += 3;
			}
		}

		return xwk;
	}
}
